#include <vector>

using namespace std;

class Solution {
public:
    int surfaceArea(vector<vector<int>>& grid) {
        int height = grid.size();
        int width = grid[0].size();
        int ans = 0;
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (grid[i][j] == 0) {
                    continue;
                }
                int area = 2 + 4 * grid[i][j];
                if (i > 0) {
                    area -= min(grid[i - 1][j], grid[i][j]);
                }
                if (i < height - 1) {
                    area -= min(grid[i + 1][j], grid[i][j]);
                }
                if (j > 0) {
                    area -= min(grid[i][j - 1], grid[i][j]);
                }
                if (j < width - 1) {
                    area -= min(grid[i][j + 1], grid[i][j]);
                }
                ans += area;
            }
        }
        return ans;
    }
};